package by.alex.dzeshko.lastfmsimple.app.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import by.alex.dzeshko.lastfmsimple.R;
import by.alex.dzeshko.lastfmsimple.adapter.TracksCursorAdapter;
import by.alex.dzeshko.lastfmsimple.app.fragment.AlbumsListFragment.Callbacks;
import by.alex.dzeshko.lastfmsimple.appstate.AppState.ScreenState;
import by.alex.dzeshko.lastfmsimple.content.Contract;
import by.alex.dzeshko.lastfmsimple.service.SearchService;
import by.alex.dzeshko.lastfmsimple.service.common.CommonService;

import com.actionbarsherlock.app.SherlockListFragment;

public class TrackListFragment extends SherlockListFragment implements
		LoaderCallbacks<Cursor> {

	private TracksCursorAdapter mCursorAdapter;

	private BroadcastReceiver mBroadcastReceiver;

	private static final String STATE_ACTIVATED_POSITION = "activated_position";

	private Callbacks mCallbacks = sCallbacks;

	private int mActivatedPosition = ListView.INVALID_POSITION;

	private static Callbacks sCallbacks = new Callbacks() {

		@Override
		public void onSearchQuerySubmited(String query) {

		}

		@Override
		public void onItemSelected(ScreenState state, Bundle arguments) {

		}

	};

	public TrackListFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mCursorAdapter = new TracksCursorAdapter(getSherlockActivity(), null);
		setListAdapter(mCursorAdapter);
		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(CommonService.ACTION_ON_ERROR)) {
					Toast.makeText(
							getSherlockActivity(),
							intent.getStringExtra(CommonService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_SHORT).show();
				} else if (action.equals(CommonService.ACTION_ON_SUCCESS)) {

				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(CommonService.ACTION_ON_ERROR);
		filter.addAction(CommonService.ACTION_ON_SUCCESS);
		getSherlockActivity().registerReceiver(mBroadcastReceiver, filter);
		getSherlockActivity().getSupportLoaderManager().initLoader(2, null,
				this);
	}

	@Override
	public void onDestroy() {
		getSherlockActivity().unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_tracks, null);
		return v;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// Restore the previously serialized activated item position.
		if (savedInstanceState != null
				&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
			setActivatedPosition(savedInstanceState
					.getInt(STATE_ACTIVATED_POSITION));
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// Activities containing this fragment must implement its callbacks.
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException(
					"Activity must implement fragment's callbacks.");
		}

		mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		// Reset the active callbacks interface to the dummy implementation.
		mCallbacks = sCallbacks;
	}

	/*
	 * @Override public void onListItemClick(ListView listView, View view, int
	 * position, long id) { super.onListItemClick(listView, view, position, id);
	 * Cursor cursor = (Cursor) listView.getItemAtPosition(position); // Notify
	 * the active callbacks interface (the activity, if the // fragment is
	 * attached to one) that an item has been selected. Bundle arguments = new
	 * Bundle(); arguments.putString(DetailActivity.MBID,
	 * cursor.getString(cursor.getColumnIndex(Contract.AlbumsColumns.MBID)));
	 * mCallbacks.onItemSelected(ScreenState.TRACK, arguments); }
	 */

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (mActivatedPosition != ListView.INVALID_POSITION) {
			// Serialize and persist the activated item position.
			outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
		}
	}

	/**
	 * Turns on activate-on-click mode. When this mode is on, list items will be
	 * given the 'activated' state when touched.
	 */
	public void setActivateOnItemClick(boolean activateOnItemClick) {
		// When setting CHOICE_MODE_SINGLE, ListView will automatically
		// give items the 'activated' state when touched.
		getListView().setChoiceMode(
				activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
						: ListView.CHOICE_MODE_NONE);
	}

	private void setActivatedPosition(int position) {
		if (position == ListView.INVALID_POSITION) {
			getListView().setItemChecked(mActivatedPosition, false);
		} else {
			getListView().setItemChecked(position, true);
		}

		mActivatedPosition = position;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
		return new CursorLoader(getSherlockActivity(),
				Contract.TracksColumns.CONTENT_URI, null,
				Contract.TracksColumns.MARKER + " = ?",
				new String[] { SearchService.SEARCHED }, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		mCursorAdapter.swapCursor(cursor);

	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mCursorAdapter.swapCursor(null);
	}

}
